package leetcode;

import java.util.ArrayList;
import java.util.List;

public class Q0022 {
    StringBuilder sb = new StringBuilder();
    ArrayList<String> res = new ArrayList<>();

    private void dfs(int n, int l, int r) {
        if (l + r == 2 * n) {
            res.add(sb.toString());
            return;
        }
        if (l < n) {
            sb.append('(');
            dfs(n, l + 1, r);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (l > r) {
            sb.append(')');
            dfs(n, l, r + 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    public List<String> generateParenthesis(int n) {
        dfs(n, 0, 0);
        return res;
    }
}
